<style scoped rel="stylesheet/scss" lang="scss">
.context-row {
  min-height: 700px;
  max-height: 900px;
}
.height-inherit {
  height: inherit;
}
.menu-border-left {
  border-right: unset;
}
.context-right-border {
  border: 1px solid #e6eef7;
  border-left: unset;
}
td .el-input-number {
  max-width: 120px;
}
.el-menu-item.is-active{
  color: #fff !important;
  background-color: #28a087 !important;
}
.el-menu-item:hover{
  color: #fff !important;
  background-color: #28a087 !important;
  i{
    color: #fff !important;
  }
}
</style>

<template>
  <el-row type="flex" class="p-30 context-row bg-white" justify="space-around">
    <el-col :span="2">
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical-demo full-height menu-border-left"
        background-color="#e6eef7"
        text-color="#494f54"
      >
        <el-menu-item index="安装" @click="changeCard(0)">
          <i class="icon-commonyuanquyunwei"/>
          <span slot="title">安装</span>
        </el-menu-item>
        <el-menu-item index="维修" @click="changeCard(1)">
          <i class="icon-commonicon_shezhi"/>
          <span slot="title">维修</span>
        </el-menu-item>
        <el-menu-item index="清洗" @click="changeCard(2)">
          <i class="icon-commonshuibiao"/>
          <span slot="title">清洗</span>
        </el-menu-item>
        <el-menu-item index="保养" @click="changeCard(3)">
          <i class="icon-commontuoguan"/>
          <span slot="title">保养</span>
        </el-menu-item>
        <el-menu-item index="移机" @click="changeCard(4)">
          <i class="icon-commonhuowudui1"/>
          <span slot="title">移机</span>
        </el-menu-item>
        <el-menu-item index="保外佣金" @click="changeCard(5)">
          <i class="icon-commonweizhigeshi"/>
          <span slot="title">保外佣金</span>
        </el-menu-item>
        <el-menu-item index="其他项目" @click="changeCard(6)">
          <i class="icon-commonyingyongguanli"/>
          <span slot="title">其他项目</span>
        </el-menu-item>
      </el-menu>
    </el-col>
    <el-col :span="22" class="context-right-border p-20">
      <el-row :gutter="5" type="flex" align="middle">
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="3">
          <label>选择品类:</label>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="6">
          <el-select v-model="condition.category" value-key="categoryId" placeholder="品类" @change="changeCategory">
            <el-option
              v-for="item in categoryData"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'out'" :span="6">
          <el-select v-model="outSelectCategory" value-key="categoryId" placeholder="选择品类" @change="outSelectCategoryAddRow">
            <el-option
              v-for="item in categoryData"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'other'" :span="3">
          <label>选择项目:</label>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'other'" :span="6">
          <el-select v-model="otherSelectData.projectParentType" value-key="id" placeholder="大项" @change="getChildenProjectData">
            <el-option
              v-for="item in projectParentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'other'" :span="6">
          <el-select v-model="otherSelectData.projectChildenType" value-key="id" placeholder="子项" >
            <el-option
              v-for="item in projectChildenTypeList"
              :key="item.id"
              :label="item.name"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'other'" :span="4">
          <el-button type="primary" @click="addOtherPriceRow" >添加项目价签</el-button>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="6" class="pr-10">
          <el-select v-model="condition.specification" value-key="specificationId" clearable placeholder="规格" @change="selectSpecificationAddRow">
            <el-option
              v-for="item in specificationData"
              :key="item.specificationId"
              :label="item.specificationName"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="6" class="pr-10">
          <el-select
            :class="priceData.length>0 && measureTypeData.length === 1?'hide-no-change':''"
            v-model="condition.measureType"
            value-key="measureTypeId"
            clearable
            placeholder="服务措施分类"
            @change="selectMeasureTypeAddColumn">
            <el-option
              v-for="item in measureTypeData"
              :key="item.measureTypeId"
              :label="item.measureTypeName"
              :value="item"
            />
          </el-select>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="3" class="pr-10">
          <el-button type="primary" @click="savePrice" >保存价签</el-button>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'out'" :span="3" class="pr-10">
          <el-button type="primary" @click="saveOutChargePrice" >保存价签</el-button>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'other'" :span="3" class="pr-10">
          <el-button type="primary" @click="saveOtherChargePrice" >保存价签</el-button>
        </el-col>

        <!-- <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="3" class="pr-10">
          <el-button type="primary" click="" >添加规格</el-button>
        </el-col>
        <el-col v-if="cardData[cardActiveIndex].serviceChargeType === 'in'" :span="4" class="pr-10">
          <el-button type="primary" click="" >添加措施分类</el-button>
        </el-col> -->
      </el-row>
      <el-row type="flex" align="middle" class="pt-20">
        <el-col :span="24">
          <!-- 保内价签 -->
          <el-row v-if="cardData[cardActiveIndex].serviceChargeType === 'in'">
            <el-table :data="priceData" :key="tableKey" border fit highlight-current-row style="width: 100%">
              <el-table-column :label="specificationColumn" prop="specificationName" width="180">
                <template slot-scope="scope">
                  {{ scope.row.specificationName }}
                  <i v-if="deleteable" @click="deleteSpecificationRow(scope.row.specificationId)"><svg-icon icon-class="close" class-name="row-delete-icon"/></i>
                </template>
              </el-table-column>
              <el-table-column v-for="item in columnHeader" :key="item" :label="item" :render-header= "renderHeaderOne" width="150">
                <template slot-scope="scope">
                  <el-input-number :precision="2" :controls="false" :min="0" :max="99999999.99" v-model="scope.row.measureTypeCharge[item]" placeholder="请输入金额" @change="cellEditChange(item,scope.row)"/>
                </template>
              </el-table-column>
            </el-table>
          </el-row>

          <!-- 保外价签 -->
          <el-row v-else-if="cardData[cardActiveIndex].serviceChargeType === 'out'">

            <el-table :data="outPriceData" border fit highlight-current-row style="width: 340px" max-height="700">
              <el-table-column prop="categoryName" label="品类名称" width="180">
                <template slot-scope="scope">
                  {{ scope.row.categoryName }}
                  <i v-if="deleteable" click=""><svg-icon icon-class="close" class-name="row-delete-icon"/></i>
                </template>
              </el-table-column>
              <el-table-column prop="outGuaranteeRake" label="抽佣(负数)" width="158">
                <template slot-scope="scope">
                  <el-input-number :precision="2" :controls="false" :min="-99999999.99" :max="0" v-model="scope.row.outGuaranteeRake" placeholder="请输入抽佣金额" />
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <!-- 其他额外价签 -->
          <el-row v-else-if="cardData[cardActiveIndex].serviceChargeType === 'other'">
            <el-row :gutter="20">
              <el-col v-if ="otherSelectData.projectParentType.description=='compute' && otherPriceData.length == 1" :span="10">
                <div v-if="otherSelectData.projectParentType.pkey=='charge_type_down_base_other_range'" >
                  <!--远程 下限类型项目-->
                  <el-row><label class="radio-label">远程费用:</label></el-row>
                  <el-row class="mt-10">
                    <el-col :span = "10">
                      <span>最小距离（公里）</span>
                    </el-col>
                    <el-col :span = "13">
                      <el-input-number :controls="false" :min="0" v-model="otherPriceData[0].lowerLimit" placeholder="起止下限" />
                    </el-col>
                  </el-row>
                  <el-row class="mt-10">
                    <el-col :span = "10">
                      <span>每公里费用（元）</span>
                    </el-col>
                    <el-col :span = "13">
                      <el-input-number :precision="2" :controls="false" :min="0" :max="99999999.99" v-model="otherPriceData[0].commission" placeholder="金额" />
                    </el-col>
                  </el-row>
                </div>
                <div v-else-if="otherSelectData.projectParentType.pkey.indexOf('charge_type_down_base_other_holes') !== -1">
                  <el-row><label class="radio-label">打孔费用:</label></el-row>
                  <el-row class="mt-10">
                    <el-col :span = "10">
                      <span>数量起止</span>
                    </el-col>
                    <el-col :span = "13">
                      <el-input-number :controls="false" :min="0" v-model="otherPriceData[0].lowerLimit" placeholder="起止下限" />
                    </el-col>
                  </el-row>
                  <el-row class="mt-10">
                    <el-col :span = "10">
                      <span>每孔费用（元）</span>
                    </el-col>
                    <el-col :span = "13">
                      <el-input-number :precision="2" :controls="false" :min="0" :max="99999999.99" v-model="otherPriceData[0].commission" placeholder="金额" />
                    </el-col>
                  </el-row>
                </div>
              </el-col>
              <el-col v-else :span="11">
                <el-table :data="otherPriceData" border fit highlight-current-row style="width: 100%">
                  <el-table-column prop="parentTypeName" label="大项" width="120">
                    <template slot-scope="scope">
                      {{ scope.row.parentTypeName }}
                      <i v-if="deleteable || !scope.row.chargeExtraId" click=""><svg-icon icon-class="close" class-name="row-delete-icon"/></i>
                    </template>
                  </el-table-column>

                  <el-table-column prop="projectTypeName" label="子项">
                    <template slot-scope="scope">
                      {{ scope.row.projectTypeName }}
                      <i v-if="deleteable" click=""><svg-icon icon-class="close" class-name="row-delete-icon"/></i>
                    </template>
                  </el-table-column>

                  <el-table-column prop="commission" label="金额" width="150">
                    <template slot-scope="scope">
                      <el-input-number :precision="2" :controls="false" :min="0" :max="99999999.99" v-model="scope.row.commission" size="small" placeholder="请输入金额" />
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>

              <el-col :span="13">
                <el-transfer
                  :filter-method="filterMethod"
                  :titles="['可选品类', '已选品类']"
                  :props="{
                    key: 'categoryId',
                    label: 'categoryName'
                  }"
                  v-model="otherSelectData.category"
                  :data="categoryData"
                  style="height: 300px"
                  filterable
                  filter-placeholder="请输入品类"/>
              </el-col>
            </el-row>
          </el-row>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import waves from '@/directive/waves/index.js' // 水波纹指令
import { listLeafCategory } from '@/api/category'
import { getSpecification } from '@/api/specification'
import { getMeasureType } from '@/api/MeasureType'
import { getParentProjectParams, getChildenParams } from '@/api/param'
import { getCharge, saveCharge, getOutCharge, saveOutCharge, getOtherCharge, saveOtherCharge } from '@/api/pricetag'
export default {
  name: 'ComponentMixinDemo',
  directives: {
    waves
  },
  data() {
    return {
      // 删除功能
      deleteable: true,
      // cardData:["安装","维修","清洗","保养","移机","保外佣金","其他项目"],
      cardData: [
        { text: '安装', serviceChargeType: 'in' },
        { text: '维修', serviceChargeType: 'in' },
        { text: '清洗', serviceChargeType: 'in' },
        { text: '保养', serviceChargeType: 'in' },
        { text: '移机', serviceChargeType: 'in' },
        { text: '保外佣金', serviceChargeType: 'out' },
        { text: '其他项目', serviceChargeType: 'other' }
      ],
      activeMenu: '安装',
      cardActiveIndex: 0,
      categoryData: [],
      specificationData: [],
      measureTypeData: [],

      tableKey: 0,

      columnHeader: [],

      // 展示控制数据
      priceData: [],
      // 请求保存数据 于 priceData行为保持一致（除删除）
      savePriceData: [],

      condition: {
        category: '',
        chargeType: '',
        specification: '',
        measureType: ''
      },

      // 保外佣金选择添加的品类对象
      outSelectCategory: {},
      outPriceData: [],

      // 其他项目服务价签
      projectParentTypeList: [],
      projectChildenTypeList: [],

      otherPriceData: [],

      // 选择的数据
      otherSelectData: {
        // projectParentType: { id: 476, name: '拉修', pkey: 'charge_type_down_base_other_laxiu' },
        projectParentType: { id: 0 },
        projectChildenType: '',
        category: []
      }

    }
  },

  computed: {
    specificationColumn: function() {
      for (var j = 0, len = this.categoryData.length; j < len; j++) {
        if (this.categoryData[j].categoryId === this.condition.category.categoryId) {
          this.forceRefreshTable()
          return this.categoryData[j].categoryName + '--规格'
        }
      }
    }
  },

  watch: {
    checkboxVal(valArr) {
      // this.formThead = this.formTheadOptions.filter(i => valArr.indexOf(i) >= 0)
      // this.key = this.key + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    }
  },

  created() {
    // 初始
    this.condition.category = { categoryId: 87, categoryName: '冰箱' }
    this.getCategoryData()
    this.getSpecificationData(this.condition.category)

    this.changeCard(0)
    this.getAllMeasureTypeData(this.cardData[this.cardActiveIndex].text)
    this.forceRefreshTable()
  },

  methods: {
    forceRefreshTable() {
      this.tableKey = this.tableKey + 1
    },

    renderHeaderOne(h, { column, $index }) {
      return h('span', [
        h('span', column.label),
        h('i', {
          style: this.deleteable ? '' : 'display: none;',
          on: {
            click: () => {
              this.deleteMeasureTypeColumn($index)
            }
          }
        }, [
          h('svg-icon', {
            style: 'margin-right:5px',
            props: { iconClass: 'close', className: 'column-delete-icon-' + $index }
          })
        ])
      ])
    },
    changeCard(index) {
      this.cardActiveIndex = index
      this.condition.chargeType = this.cardData[index].text
      this.condition.specification = {}
      this.condition.measureType = {}
      this.otherSelectData.projectChildenType = ''
      this.loadTableData(index)
    },
    loadTableData(index) {
      if (this.cardData[index].serviceChargeType === 'in') {
        this.getSpecificationData(this.condition.category)
        this.getAllMeasureTypeData(this.cardData[index].text)
        this.getChargeData()
      } else if (this.cardData[index].serviceChargeType === 'out') { // 保外佣金
        // 再写个表 隐藏 显示
        this.getOutChargeData()
      } else if (this.cardData[index].serviceChargeType === 'other') { // 其他项目
        // 请求大项
        this.getParentProjectData()
        this.getChildenProjectData()
        this.getOtherChargeData()
      }
      this.forceRefreshTable()
    },

    getCategoryData() {
      var data = {}
      listLeafCategory(data).then(
        response => {
          if (response.data.status === 'success') {
            this.categoryData = response.data.data
          } else {
            this.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },

    getSpecificationData(category) {
      if (category) {
        getSpecification(category.categoryId).then(
          response => {
            if (response.data.status === 'success') {
              this.specificationData = response.data.data
              // this.changeCard(0)
              // this.getAllMeasureTypeData(this.cardData[this.cardActiveIndex].text)
              this.forceRefreshTable()
            } else {
              this.$message({
                message: '品类规格失败' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }
    },
    getAllMeasureTypeData(chargeType) {
      getMeasureType(chargeType).then(
        response => {
          if (response.data.status === 'success') {
            this.measureTypeData = response.data.data
            if (response.data.data.length === 1) {
              this.condition.measureType = response.data.data[0]
            }
          } else {
            this.$message({
              message: '措施分类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },

    getChargeData() {
      var data = {
        orderServiceType: this.condition.chargeType,
        categoryId: this.condition.category.categoryId
      }
      getCharge(data).then(
        response => {
          if (response.data.status === 'success') {
            this.priceData = response.data.data.data
            this.savePriceData = this.objDeepCopy(response.data.data.data)
            if (response.data.data.measureTypeColumn) {
              this.columnHeader = response.data.data.measureTypeColumn
            } else {
              this.columnHeader = []
              this.condition.measureType = {}
            }
          } else {
            this.$message({
              message: '品类加载失败' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    changeCategory() {
      var self = this
      self.condition.measureType = {}
      self.condition.specification = {}
      self.loadTableData(self.cardActiveIndex)
    },
    // 选择规格添加 行
    selectSpecificationAddRow(val) {
      if (val || val.specificationId) {
        var specificationRow = {
          categoryId: this.condition.category.categoryId,
          categoryName: this.condition.category.categoryName,
          chargeType: this.condition.chargeType,
          specificationId: val.specificationId,
          specificationName: val.specificationName,
          measureTypeCharge: {},
          measureTypeChargeId: {}
        }
        for (var i = this.priceData.length - 1; i >= 0; i--) {
          if (this.priceData[i].specificationId === val.specificationId) {
            this.$message({
              message: '规格{' + val.specificationName + '}价签已有同规格，请直接修改保存',
              type: 'warning'
            })
            return
          }
        }
        this.priceData.push(specificationRow)
        // 添加的规格在保存数据中存在 就忽略
        for (i = this.savePriceData.length - 1; i >= 0; i--) {
          if (this.savePriceData[i].specificationId === val.specificationId) {
            return
          }
        }
        this.savePriceData.push(specificationRow)
      }
    },
    // 删除规格行 将savePriceData对应的价格数据置空 priceData对应数据删除
    deleteSpecificationRow(specificationId) {
      for (var i = this.savePriceData.length - 1; i >= 0; i--) {
        if (this.savePriceData[i].specificationId === specificationId) {
          this.savePriceData[i].measureTypeCharge = {}
        }
      }
      this.priceData = this.priceData.filter(function(item) {
        return item.specificationId !== specificationId
      })
    },
    // 编辑 使 savePriceData 和 priceData 数据保持一致
    cellEditChange(measureTypeName, rowData) {
      console.debug(measureTypeName)
      console.debug(rowData)
      for (var i = this.savePriceData.length - 1; i >= 0; i--) {
        if (this.savePriceData[i].specificationId === rowData.specificationId) {
          this.savePriceData[i].measureTypeCharge[measureTypeName] = rowData.measureTypeCharge[measureTypeName]
        }
      }
    },
    // 选择措施分类 添加列
    selectMeasureTypeAddColumn(measureType) {
      var self = this
      let obj = {}
      obj = self.columnHeader.find(item => {
        return item === measureType.measureTypeName
      })
      if (!obj || typeof obj === 'undefined') {
        if (measureType && measureType.measureTypeName) {
          self.columnHeader.push(measureType.measureTypeName)
        }
      } else {
        self.$message({
          message: '已存在相同措施分类价签，不能重复添加',
          type: 'warning'
        })
      }
    },
    // 把列数组删除 savePriceData 对应的价格置空 priceData 对应删除
    deleteMeasureTypeColumn(columnNum) {
      console.debug(columnNum)
      var columnIndex = columnNum - 1
      var measureTypeName = this.columnHeader[columnIndex]
      this.columnHeader = this.columnHeader.filter(function(item, index) {
        return index !== columnIndex
      })
      for (var i = this.priceData.length - 1; i >= 0; i--) {
        this.priceData[i].measureTypeCharge[measureTypeName] = ''
      }
      for (i = this.savePriceData.length - 1; i >= 0; i--) {
        this.savePriceData[i].measureTypeCharge[measureTypeName] = ''
      }
    },

    // 保存价签 将savePriceData 数据传给后台
    savePrice() {
      var self = this
      let obj = {}
      obj = self.savePriceData.find(item => {
        if (item.categoryId !== null && item.specificationId !== null && item.chargeType !== null && item.measureTypeCharge && item.measureTypeCharge !== undefined) {
          for (var prop in item.measureTypeCharge) {
            if (prop !== null) {
              continue
            } else {
              return item
            }
          }
        } else {
          return item
        }
      })
      if (!obj || typeof obj === 'undefined') {
        var params = { dataStr: JSON.stringify(this.savePriceData) }
        console.debug(params.dataStr)

        this.$confirm('确认保存?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          saveCharge(params).then(
            response => {
              if (response.data.status === 'success') {
                self.loadTableData(self.cardActiveIndex)
                this.$message({
                  message: '保存成功！',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '保存失败：' + response.data.messge,
                  type: 'warning'
                })
              }
            }).catch(() => {
            this.$message({
              type: 'info',
              message: '网络请求失败'
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      } else {
        self.$message({
          message: '系统错误，请刷新页面后重试',
          type: 'warning'
        })
      }
      // for (var i = this.savePriceData.length - 1; i >= 0; i--) {
      //   for (var j = this.savePriceData.length - 1; j >= 0; j--) {

      //     // if (this.savePriceData[i].measureTypeCharge[this.columnHeader[j]] === undefined) {
      //     //   this.$message({
      //     //     message: '部分数据为空！',
      //     //     type: 'error'
      //     //   })
      //     //   return
      //     // }
      //   }
      // }
    },
    // 保外选择品类 添加数据
    outSelectCategoryAddRow(category) {
      for (var i = this.outPriceData.length - 1; i >= 0; i--) {
        if (this.outPriceData[i].categoryId === category.categoryId) {
          console.debug(category)
          this.$message({
            type: 'warning',
            message: '保外佣金已有{' + category.categoryName + '}的抽佣，请直接修改！'
          })
          return
        }
      }
      this.outPriceData.push({ categoryName: category.categoryName, categoryId: category.categoryId })
    },

    getOutChargeData() {
      getOutCharge().then(
        response => {
          if (response.data.status === 'success') {
            for (var i = response.data.data.length - 1; i >= 0; i--) {
              if (response.data.data[i].outGuaranteeRake === null) {
                response.data.data[i].outGuaranteeRake = undefined
              }
            }
            this.outPriceData = response.data.data
          } else {
            this.$message({
              message: '加载保外佣金失败：' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },

    saveOutChargePrice() {
      var self = this
      for (var i = this.outPriceData.length - 1; i >= 0; i--) {
        if (this.outPriceData[i].outGuaranteeRake === undefined) {
          this.$message({
            message: '部分数据为空！',
            type: 'error'
          })
          return
        }
      }
      // 将 保外佣金数据  修改和 新增分开
      var insertList = this.outPriceData.filter(function(item) {
        return item.outServiceChargeId === undefined
      })

      var updateList = this.outPriceData.filter(function(item) {
        return item.outServiceChargeId !== undefined && item.outServiceChargeId !== null
      })

      var params = {
        insertStr: JSON.stringify(insertList),
        updateStr: JSON.stringify(updateList)
      }
      console.debug(params)

      this.$confirm('确认保存?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        saveOutCharge(params).then(
          response => {
            if (response.data.status === 'success') {
              self.loadTableData(self.cardActiveIndex)
              this.$message({
                message: '保存成功！',
                type: 'success'
              })
            } else {
              this.$message({
                message: '保存失败：' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },

    filterMethod(query, item) {
      return item.categoryName.indexOf(query) > -1
    },

    getParentProjectData() {
      getParentProjectParams().then(
        response => {
          if (response.data.status === 'success') {
            this.projectParentTypeList = response.data.data
          } else {
            this.$message({
              message: '加载服务项目失败：' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },

    getChildenProjectData() {
      this.otherSelectData.projectChildenType = ''
      this.getOtherChargeData()
      getChildenParams(this.otherSelectData.projectParentType.id).then(
        response => {
          if (response.data.status === 'success') {
            this.projectChildenTypeList = response.data.data
          } else {
            this.$message({
              message: '加载服务项目失败：' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },
    // 添加项目价签
    addOtherPriceRow() {
      if (!this.otherSelectData.projectChildenType.id) {
        this.$message({
          message: '请选择子项目',
          type: 'warning'
        })
        return
      }
      for (var i = this.otherPriceData.length - 1; i >= 0; i--) {
        if (this.otherPriceData[i].projectType === this.otherSelectData.projectChildenType.pkey) {
          this.$message({
            message: '已有相同的子项目价签，请直接修改',
            type: 'warning'
          })
          return
        }
      }

      var row = {
        parentType: this.otherSelectData.projectParentType.pkey,
        parentTypeName: this.otherSelectData.projectParentType.name,
        projectType: this.otherSelectData.projectChildenType.pkey,
        projectTypeName: this.otherSelectData.projectChildenType.name,
        lower_limit: null,
        commission: ''
      }
      this.otherPriceData.push(row)
    },

    getOtherChargeData() {
      // 用大项查询价签
      if (this.otherSelectData.projectParentType.id) {
        var param = { parentProjectTypeId: this.otherSelectData.projectParentType.id, parentProjectType: this.otherSelectData.projectParentType.pkey }
        getOtherCharge(param).then(
          response => {
            if (response.data.status === 'success') {
              var resultData = response.data.data
              // 做处理将品类取出来 并将数据去重 作为展示数据
              var categoryIdArr = []// arr.indexOf(arr[i])==i
              var noRepeatData = []
              var cache = {}
              // 按子项分组
              for (var i = resultData.length - 1; i >= 0; i--) {
                if (!cache[resultData[i].projectType]) {
                  noRepeatData.push(resultData[i])
                  cache[resultData[i].projectType] = true
                }
              }
              // 按品类分组
              for (var j = resultData.length - 1; j >= 0; j--) {
                if (!cache[resultData[j].categoryId]) {
                  categoryIdArr.push(resultData[j].categoryId)
                  cache[resultData[j].categoryId] = true
                }
              }
              debugger
              if (noRepeatData.length === 0 && this.otherSelectData.projectParentType.description === 'compute') { // 没有数据要加一个空对象，否则会绑定出错
                noRepeatData.push({ projectType: this.otherSelectData.projectParentType.pkey, lowerLimit: '', commission: '' })
              }
              this.otherPriceData = noRepeatData
              this.otherSelectData.category = categoryIdArr
            } else {
              this.$message({
                message: '加载额外项目价签失败：' + response.data.messge,
                type: 'warning'
              })
            }
          }).catch(() => {
          this.$message({
            type: 'info',
            message: '网络请求失败'
          })
        })
      }
    },

    saveOtherChargePrice() {
      var self = this
      for (var i = this.otherPriceData.length - 1; i >= 0; i--) {
        if (this.otherPriceData[i].commission === undefined) {
          this.$message({
            message: '部分数据为空！',
            type: 'error'
          })
          return
        }
      }
      var projectTypePriceArr = []
      for (var j = this.otherPriceData.length - 1; j >= 0; j--) {
        projectTypePriceArr.push({
          projectType: this.otherPriceData[j].projectType,
          commission: this.otherPriceData[j].commission,
          lowerLimit: this.otherPriceData[j].lowerLimit })
      }

      var params = {
        categoryIdsStr: JSON.stringify(this.otherSelectData.category),
        projectTypePriceStr: JSON.stringify(projectTypePriceArr)
      }
      console.debug(this.otherSelectData.category)
      console.debug(projectTypePriceArr)

      saveOtherCharge(params).then(
        response => {
          if (response.data.status === 'success') {
            self.loadTableData(self.cardActiveIndex)
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
          } else {
            this.$message({
              message: '加载额外项目价签失败：' + response.data.messge,
              type: 'warning'
            })
          }
        }).catch(() => {
        this.$message({
          type: 'info',
          message: '网络请求失败'
        })
      })
    },

    // 复杂对象深度拷贝
    objDeepCopy(source) {
      var sourceCopy = source instanceof Array ? [] : {}
      for (var item in source) {
        sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item]
      }
      return sourceCopy
    }
  }

}
</script>
